package cz.byteworks.sandbox.html5.newsbox.service.impl;

import java.util.Date;
import java.util.List;
import java.util.Random;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.gson.Gson;

import cz.byteworks.sandbox.html5.newsbox.dao.IMessageDAO;
import cz.byteworks.sandbox.html5.newsbox.exception.RepositoryException;
import cz.byteworks.sandbox.html5.newsbox.exception.ServiceException;
import cz.byteworks.sandbox.html5.newsbox.model.NewsMessage;
import cz.byteworks.sandbox.html5.newsbox.service.INewsService;

@Service(value = "newsService")
public class BasicNewsService implements INewsService {

    @Autowired
    private IMessageDAO messageDAO;
    
    private Gson gson = new Gson();
    
    @Override
    public String getUnreadMessagesJSONArray() throws ServiceException {
        try {
            List<NewsMessage> messages = messageDAO.loadNewMessages();
            return messages.isEmpty() ? null : gson.toJson(messages);
        } catch (RepositoryException e) {
            throw new ServiceException(e.getRepositoryType().getUserFriendlyName() + ": " + e.getRepositoryType().getUnavailableMessage(), e);
        }
        
    }

    @Override
    public void sendJSONMessage(String jsonMessage) throws ServiceException {
        NewsMessage message = gson.fromJson(jsonMessage, NewsMessage.class);
        Date actualDate = new Date();
        Random random = new Random(actualDate.getTime());
        message.setMessageId(random.nextLong());
        message.setSentDate(actualDate);
        try {
            messageDAO.sendMessage(message);
        } catch (RepositoryException e) {
            throw new ServiceException(e.getRepositoryType().getUserFriendlyName() + ": " + e.getRepositoryType().getUnavailableMessage(), e);
        }
    }

}
